package net.tv90.shoppingserver.service;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import net.tv90.shoppingserver.dao.CartRepository;
import net.tv90.shoppingserver.dao.GoodRepository;
import net.tv90.shoppingserver.dao.UserRepository;
import net.tv90.shoppingserver.exception.ServerException;
import net.tv90.shoppingserver.model.domain.Cart;
import net.tv90.shoppingserver.model.domain.Good;
import net.tv90.shoppingserver.model.domain.User;
import net.tv90.shoppingserver.model.dto.CartDTO;
import net.tv90.shoppingserver.model.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartService {

    @Autowired
    GoodRepository goodRepository;

    @Autowired
    CartRepository cartRepository;

    @Autowired
    UserRepository userRepository;

    public void addGoodToCart(CartDTO dto) {
        User user = userRepository.findById(StpUtil.getLoginIdAsInt())
                .orElseThrow(() -> new ServerException("未找到用户", HttpStatus.BAD_REQUEST));
        Good good = goodRepository.findById(dto.getGoodId())
                .orElseThrow(() -> new ServerException("未找到商品", HttpStatus.BAD_REQUEST));
        Cart cart = cartRepository.findCartByUserAndGood(user, good);
        //更新数量或创建新的购物车项
        if (cart != null) {
            cart.setNum(cart.getNum() + dto.getNum());
            cartRepository.save(cart);
        } else {
            Cart added = Cart.builder()
                    .user(user)
                    .num(dto.getNum())
                    .good(good)
                    .build();
            cartRepository.save(added);
        }
        log.info("用户{}将商品{}(id={}) {}件加入购物车", user.getUsername(), good.getName(), good.getId(), dto.getNum());
    }

    public void removeGoodToCart(Integer id) {
        User user = userRepository.findById(StpUtil.getLoginIdAsInt())
                .orElseThrow(() -> new ServerException("未找到用户", HttpStatus.BAD_REQUEST));
        Good good = goodRepository.findById(id)
                .orElseThrow(() -> new ServerException("未找到商品", HttpStatus.BAD_REQUEST));
        Cart cart = cartRepository.findCartByUserAndGood(user, good);
        if (cart != null) {
            cartRepository.delete(cart);
        } else {
            throw new ServerException("购物车中不存在该商品", HttpStatus.BAD_REQUEST);
        }
    }

    public void updateCartItemNum(CartDTO dto) {
        User user = userRepository.findById(StpUtil.getLoginIdAsInt())
                .orElseThrow(() -> new ServerException("未找到用户", HttpStatus.BAD_REQUEST));
        Good good = goodRepository.findById(dto.getGoodId())
                .orElseThrow(() -> new ServerException("未找到商品", HttpStatus.BAD_REQUEST));
        Cart cart = cartRepository.findCartByUserAndGood(user, good);
        if (cart != null) {
            cart.setNum(dto.getNum());
            cartRepository.save(cart);
        } else {
            throw new ServerException("购物车中不存在该商品", HttpStatus.BAD_REQUEST);
        }
    }

    public List<CartVO> getAllCartItems(Integer userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ServerException("未找到用户", HttpStatus.BAD_REQUEST));
        List<Cart> carts = Optional.ofNullable(cartRepository.findCartsByUser(user))
                .orElse(Collections.emptyList());
        return carts.stream()
                .map(cart -> new CartVO(cart.getNum(), cart.getGood()))
                .collect(Collectors.toList());
    }
}
